﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace ThreeDWorld
{
    public class KeyFrame
    {
        private Vector3[] _Positions;
        private Vector3[] _Normals;

        public KeyFrame(ContentReader reader, short[] indices)
        {
            _Positions = new Vector3[reader.ReadInt32()];
            _Normals = new Vector3[_Positions.Length];

            for (int i = 0; i != _Positions.Length; i++)
            {
                _Positions[i] = reader.ReadVector3();
                _Normals[i] = Vector3.Zero;
            }

            for (int i = 0; i != indices.Length; )
            {
                Vector3 a = _Positions[indices[i + 0]];
                Vector3 b = _Positions[indices[i + 1]];
                Vector3 c = _Positions[indices[i + 2]];
                Vector3 n = Vector3.Normalize(Vector3.Cross(c - b, b - a));

                for (int j = 0; j != 3; j++, i++)
                {
                    _Normals[indices[i]] += n;
                }
            }

            for (int i = 0; i != _Normals.Length; i++)
            {
                _Normals[i].Normalize();
            }

            Bounds = BoundingBox.CreateFromPoints(_Positions);
        }

        public BoundingBox Bounds
        {
            get;
            private set;
        }

        public BoundingBox LerpBounds(KeyFrame f, float amount)
        {
            return new BoundingBox(Vector3.Lerp(Bounds.Min, f.Bounds.Min, amount), Vector3.Lerp(Bounds.Max, f.Bounds.Max, amount));
        }

        public void Lerp(KeyFrame f, VertexPositionNormalTexture[] vertices, short[] indices, float amount)
        {
            for (int i = 0; i != indices.Length; i++)
            {
                VertexPositionNormalTexture vertex = vertices[i];
                int j = indices[i];

                vertex.Position = Vector3.Lerp(_Positions[j], f._Positions[j], amount);
                vertex.Normal = Vector3.Lerp(_Normals[j], f._Normals[j], amount);

                vertices[i] = vertex;
            }
        }
    }
}
